<!--
 * @Author: huangmorong@mrcdevlab.com
 * @Date: 2025-01-07 14:58:57
 * @LastEditors: huangmorong@mrcdevlab.com
 * @LastEditTime: 2025-03-06 11:38:17
 * @FilePath: \mrc-performance\src\components\mrc_ess_UploadAttachment.vue
 * @Description: 
-->
<template>
    <div class="upload-file" :class="{ 'pl-2 pr-2 mb-8': props.label }">
        <!-- 標題 -->
        <div class="mb-4 flex" v-if="props.label" :style="{ opacity: props.label == '#' ? 0 : 1 }">
            <div class="text-text--primary text-[14px] leading-[14px] font-[500]">{{ props.label }}</div>
        </div>
        <div class="flex flex-wrap">
            <!-- 上傳區域 -->
            <div class="relative flex align-center justify-center flex-col border border-dashed h-[160px] min-w-[256px] w-[256px] rounded-[5px] mr-6 _upload-file-input"
                v-if="props.isShowFileInput">
                <!-- 上傳圖標 -->
                <div class="w-[56px] h-[56px] flex align-center justify-center">
                    <svg-icon iconClass="file-upload" size="40"></svg-icon>
                </div>
                <!-- 上傳文字 -->
                <div class="flex align-center min-h-[32px]">
                    <span class="text-primary mr-2 text-[14px] leading-[14px] font-[700]">{{ $t('text_browse') }}</span>
                    <span class="text-text--secondary text-[14px] leading-[18px] font-[400]">{{ $t('text_or_drop_files_to_update') }}</span>
                </div>
                <!-- 提示文字 -->
                <div class="font-[400] text-[12px] leading-[16px]" v-if="hint">
                    {{ hint }}
                </div>
                <!-- input -->
                <mrc_ess_FileInput :multiple="props.multiple" :disabled="props.disabled" :readonly="props.readonly"
                    :accept="props.accept" :uploadFileType="props.uploadFileType" @changeFile="changeFile">
                </mrc_ess_FileInput>
            </div>
            <!-- 附件列表 -->
            <div class="flex-grow">
                <div v-for="(item, index) in fileList" :key="item.id" class="flex align-center pt-[5px] pb-[5px]" :class="{
                    'pl-2': props.isShowDel
                }">
                    <!-- 附件圖標 -->
                    <svg-icon iconClass="attachment" size="16"></svg-icon>
                    <!-- 附件名稱 -->
                    <div class="ml-1 flex-grow w-[100px] truncate text-[14px] text-text--primary cursor-pointer underline"
                        @click="preview(item)">{{ item.name }}</div>
                    <!-- 附件尺寸 -->
                    <div class="ml-1 text-text--disabled text-[12px]">{{ item.sizeText }}</div>
                    <!-- 附件刪除 -->
                    <div class="w-[24px] h-[24px] flex align-center justify-center ml-4 cursor-pointer"
                        @click="delFile(item, index)" v-if="isUploading == false && props.isShowDel">
                        <svg-icon iconClass="cancel" size="20"></svg-icon>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, onBeforeMount, readonly } from 'vue';
import { useCurrentInstance } from "@Hooks/index.ts";
const proxy = useCurrentInstance().proxy;
const emit = defineEmits([]);
const props = defineProps({
    // 是否禁用
    disabled: {
        type: Boolean,
        default: false,
    },
    // 是否只讀
    readonly: {
        type: Boolean,
        default: false,
    },
    //上传文件规则
    uploadFileType: {
        default: () => {
            return /\.(png|jpg|gif|jpeg|webp|PNG|JPG)$/;
        },
    },
    // 提示
    hint: {
        type: String,
        default: ""
    },
    // 標題
    label: {
        type: String,
        default: ""
    },
    // 文件類型
    accept: {
        type: String,
        default: 'image/*'
    },
    // 是否可以多選
    multiple: {
        type: Boolean,
        default: true
    },
    // 是否顯示上傳區域
    isShowFileInput: {
        type: Boolean,
        default: true
    },
    // 是否顯示刪除
    isShowDel: {
        type: Boolean,
        default: true
    }
})
// 文件列表
const fileList = reactive<any>([]);
// 是否正在上传
const isUploading = ref(false);
/**
 * 预览文件
 */
function preview(item) {

}
/**
 * 添加文件
 * @param files 
 */
function changeFile(file: any) {
    fileList.push({
        file: file,
        size: file.size,
        sizeText: proxy.$utils.getFileSize(file.size),
        name: file.name,
        type: file.type,
        id: new Date().getTime(),
        status: 0, // 0未上传 1上传中 2已上传 3上传失败
        uploadSize: 0,
        url: ""
    })
}
/**
 * 删除文件
 * @param item 
 * @param index 
 */
function delFile(item: any, index: number) {
    fileList.splice(index, 1);
}
/**
 * 上傳
 * 给外部调用的上传方法
 */
function upload() {
    if (!fileList || !fileList.length) {
        return;
    }
}
/**
 * 上传到服务器
 */
function uploadToCloud() {
    return new Promise((resolve, reject) => {
        resolve(1);
    })
}
// function loadFiles(files) {
//     const promises = []
//     for (const item of files) {
//         promises.push(readFile(item))
//     }
//     return Promise.all(promises);
// }
// 利用 promise 封装一个生成 base64的 函数，因为 onload 事件不是同步的，它需要事件处理
// function readFile(file) {
//     return new Promise((resolve, reject) => {
//         const reader = new FileReader();
//         reader.onload = (event) => {
//             const result = reader.result;
//             if (typeof result === 'string') {
//                 resolve(result);
//             } else {
//                 reject(new Error("Failed to read file"));
//             }
//         };
//         reader.onerror = (event) => {
//             reject(event.target.error);
//         };
//         // 参数file: 从中读取的 Blob 或 File 对象
//         reader.readAsDataURL(file);
//     });
// }
defineExpose({
    upload
})
</script>

<style scoped>
/* 手机端兼容 */
@media screen and (max-width: 960px) {
    .upload-file ._upload-file-input {
        margin-right: 0 !important;
        width: 100% !important;
        margin-bottom: 4px;
    }
}
</style>